package com.sk.skplanet.commute.daofactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.sk.skplanet.commute.vo.Data;

public class DBdownloadTask extends AsyncTask<Void, String, Boolean> {
	private ProgressDialog dialog;
	private Context context;

	public DBdownloadTask(Context context) {
		this.context = context;
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		// TODO Auto-generated method stub

		try {
			URL url = new URL(Data.URL_DBSERVER_PATH + Data.FileNAME);
			URLConnection connection = url.openConnection();
			int length = connection.getContentLength();
			// progress.setMax(length);

			InputStream is = null;
			FileOutputStream fos = null;
			BufferedOutputStream bos = null;
			boolean success = false;
			try {
				is = connection.getInputStream();

				File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + Data.FilePATH);
				if (!dir.exists()) dir.mkdirs();
				File target = new File(dir.getAbsolutePath() + Data.FileNAME);
				if (!target.exists()) target.createNewFile();
				else {
					target.delete();
					target.createNewFile();
				}

				fos = new FileOutputStream(target);
				bos = new BufferedOutputStream(fos);

				byte[] buf = new byte[1024];
				boolean downloadFlag = true;
				int l = 0;
				while ((l = is.read(buf)) > 0) {
					// tmpLength += l;
					// Log.i(S.TAG, tmpLength + " received.");
					if (!downloadFlag) break;
					bos.write(buf, 0, l);
					// activity.runOnUiThread(new Runnable() {
					// public void run() {
					// progress.setProgress(tmpLength);
					// }
					// });
				}
				success = true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					bos.close();
				} catch (Exception e) {}
				try {
					fos.close();
				} catch (Exception e) {}
				try {
					is.close();
				} catch (Exception e) {}
				// dialog.dismiss();
				// wakeLock.release();
			}

			// 성공 시 압축 해제하고, 파일명 변경
			if (success) {

			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return null;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);

		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + Data.FilePATH);
		if (!dir.exists()) dir.mkdirs();
		File target = new File(dir.getAbsolutePath() + Data.FileNAME);
		if (!target.exists()) {
			new LocalDaoFactory(2);
		} else new LocalDaoFactory();

		if (dialog != null) dialog.dismiss();
		Toast.makeText(context, "다운이 완료되었습니다.", Toast.LENGTH_SHORT).show();

	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		dialog = ProgressDialog.show(context, "", "다운로드 중입니다.", true);
	}

}
